<template>
  <div class="app-container">
    <div style="width: 40%; margin: auto">

      <el-steps :active="step" simple style="margin-bottom: 20px">
        <el-step title="验证身份"/>
        <el-step title="设置密码"/>
        <el-step title="改密成功"/>
      </el-steps>

      <el-form
        v-show="step === 1"
        ref="step1"
        :model="passwordRequest"
        label-width="100px"
        label-position="top"
        style="width: 70%; margin: auto">
        <el-form-item>
          <el-select v-model="choice" placeholder="请选择">
            <el-option label="通过邮箱验证" value="email"/>
            <el-option label="通过手机验证" value="phone"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="choiceValue" disabled>
            <template v-if="choice === 'email'" slot="prepend">原邮箱</template>
            <template v-else slot="prepend">原手机</template>
          </el-input>
          <span v-if="choiceTip === 1" style="font-size: small; color: grey">
            当前未绑定邮箱，请先<el-button type="text" @click="gotoEmail">绑定邮箱</el-button>
          </span>
          <span v-if="choiceTip === 2" style="font-size: small; color: grey">
            当前未绑定手机，请先<el-button type="text" @click="gotoPhone">绑定手机</el-button>
          </span>
        </el-form-item>
        <el-form-item
          :rules="[
            { required: true, validator: codeRule, trigger: 'blur' }
          ]"
          prop="code">
          <el-input v-model="passwordRequest.code" placeholder="请输入验证码">
            <el-button
              v-if="showBtn"
              slot="append"
              :disabled="choiceTip !== 0 || disableBtn"
              type="text"
              plain
              @click="getCode">
              获取验证码
            </el-button>
            <span v-else slot="append">{{ countTime }} s</span>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="choiceTip !== 0 || disableNext" type="primary" style="width: 100%" @click="nextStep">
            下一步
          </el-button>
        </el-form-item>
      </el-form>

      <el-form
        v-show="step === 2"
        ref="savePassword"
        :model="passwordRequest"
        label-width="100px">
        <el-form-item
          :rules="[
            { required: true, message: '请输入当前密码', trigger: 'blur' }
          ]"
          prop="oldPassword"
          label="当前密码">
          <el-input :type="pwdType1" v-model="passwordRequest.oldPassword" placeholder="请输入当前密码"/>
          <span class="show-pwd" @click="showPwd1">
            <svg-icon icon-class="eye"/>
          </span>
        </el-form-item>
        <el-form-item
          :rules="[
            { required: true, message: '修改密码不能为空', trigger: 'blur' },
            { validator: passwordRule, trigger: 'blur' }
          ]"
          prop="newPassword"
          label="修改密码"
        >
          <el-input :type="pwdType2" v-model="passwordRequest.newPassword" placeholder="密码由8-16位数字、字母或符号组成"/>
          <span class="show-pwd" @click="showPwd2">
            <svg-icon icon-class="eye"/>
          </span>
        </el-form-item>
        <el-form-item
          :rules="[
            { required: true, message: '确认密码不能为空', trigger: 'blur' },
            { validator: rePasswordRule, trigger: 'blur' }
          ]"
          prop="rePassword"
          label="确认密码"
        >
          <el-input :type="pwdType3" v-model="passwordRequest.rePassword" placeholder="两次密码需保持一致"/>
          <span class="show-pwd" @click="showPwd3">
            <svg-icon icon-class="eye"/>
          </span>
        </el-form-item>
        <el-form-item label="密码强度">
          <password-strength v-model="passwordRequest.newPassword" style="padding-top: 10px;"/>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="saveBtn" type="primary" plain style="width: 100%" @click="saveChange">保存</el-button>
        </el-form-item>
      </el-form>

    </div>
  </div>
</template>

<script>

import PasswordStrength from '@/components/PasswordStrength'

import codeApi from '@/api/ucenter/code'
import userApi from '@/api/ucenter/user'

export default {
  name: 'Password',

  components: { PasswordStrength },

  data() {
    return {
      choice: 'email',
      step: 1,
      resetPasswodFlag: false,
      passwordRequest: {
        oldPassword: '',
        newPassword: '',
        rePassword: '',
        code: ''
      },
      pwdType1: 'password',
      pwdType2: 'password',
      pwdType3: 'password',
      disableBtn: false,
      disableNext: false,
      showBtn: true,
      countTime: 60,
      saveBtn: false
    }
  },

  computed: {

    choiceValue() {
      if (this.choice === 'email') {
        if (this.$route.params.email === undefined || this.$route.params.email === '') {
          return ''
        }
        return this.$route.params.email.substr(0, 3) + ' * * * ' + this.$route.params.email.substr(this.$route.params.email.indexOf('@'))
      } else {
        if (this.$route.params.phone === undefined || this.$route.params.phone === '') {
          return ''
        }
        return this.$route.params.phone.substr(0, 3) + ' * * * * ' + this.$route.params.phone.substr(7)
      }
    },

    choiceTip() {
      if (this.choice === 'email' && this.$route.params.email === '') {
        return 1
      }
      if (this.choice === 'phone' && this.$route.params.phone === '') {
        return 2
      }
      return 0
    }
  },

  created() {
    if (this.$route.params.email === undefined && this.$route.params.phone === undefined) {
      this.$router.push({ path: '/ucenter/profile' })
    }
  },

  mounted() {
    window.onbeforeunload = function(e) {
      e = e || window.event
      console.log(e)
      // 兼容IE8和Firefox 4之前的版本
      if (e) {
        e.returnValue = '关闭提示'
      }

      // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
      return '关闭提示'
    }
  },

  methods: {

    passwordRule(rule, value, callback) {
      if (value.length < 6) {
        callback(new Error('密码长度不能小于6位'))
      }
      if (value.length > 16) {
        callback(new Error('密码长度不能大于16位'))
      }
      if (/([\u4E00-\u9FA5])+/.test(value)) {
        callback(new Error('密码不能包含汉字'))
      }
      let mode = 0
      if (/\d/.test(value)) { // 数字
        mode++
      }
      if (/[a-z]/.test(value)) { // 小写
        mode++
      }
      if (/[A-Z]/.test(value)) { // 大写
        mode++
      }
      if (/\W/.test(value)) { // 特殊字符
        mode++
      }
      if (mode < 2) {
        callback(new Error('密码至少需包含两种以上字符'))
      }
      callback()
    },

    rePasswordRule(rule, value, callback) {
      if (value !== this.passwordRequest.newPassword) {
        callback(new Error('两次密码输入不一致'))
      }
      callback()
    },

    codeRule(rule, value, callback) {
      if (!/^\d{6}$/.test(value)) {
        callback(new Error('请输入6位数字验证码'))
      }
      callback()
    },

    showPwd1() {
      if (this.pwdType1 === 'password') {
        this.pwdType1 = ''
      } else {
        this.pwdType1 = 'password'
      }
    },

    showPwd2() {
      if (this.pwdType2 === 'password') {
        this.pwdType2 = ''
      } else {
        this.pwdType2 = 'password'
      }
    },

    showPwd3() {
      if (this.pwdType3 === 'password') {
        this.pwdType3 = ''
      } else {
        this.pwdType3 = 'password'
      }
    },

    gotoEmail() {
      this.$router.push({ name: '邮箱设置', params: { email: '' }})
    },

    gotoPhone() {
      this.$router.push({ name: '手机设置', params: { phone: '' }})
    },

    getCode() {
      if (this.choice === 'email') {
        this.disableBtn = true
        codeApi.sendMailCode(this.$route.params.email).then(res => {
          this.disableBtn = false
          this.showBtn = false
          this.timer = setInterval(() => {
            this.countTime--
            if (this.countTime === 0) {
              this.countTime = 60
              this.showBtn = true
              clearInterval(this.timer)
            }
          }, 1000)
          this.$message({
            type: 'success',
            message: res.result
          })
        }).catch(error => {
          this.disableBtn = false
          console.log(error)
        })
      } else {
        this.disableBtn = true
        codeApi.sendSmsCode(this.$route.params.phone).then(res => {
          this.disableBtn = false
          this.showBtn = false
          this.timer = setInterval(() => {
            this.countTime--
            if (this.countTime === 0) {
              this.countTime = 60
              this.showBtn = true
              clearInterval(this.timer)
            }
          }, 1000)
          this.$message({
            type: 'success',
            message: res.result
          })
        }).catch(error => {
          this.disableBtn = false
          console.log(error)
        })
      }
    },

    nextStep() {
      this.$refs.step1.validate(valid => {
        if (valid) {
          if (this.choice === 'email') {
            this.disableNext = true
            codeApi.verifyEmailCode(this.passwordRequest.code).then(res => {
              this.disableNext = false
              this.$message({
                type: 'success',
                message: res.result
              })
              this.step = 2
            }).catch(error => {
              this.disableNext = false
              console.log(error)
            })
          } else {
            this.disableNext = true
            codeApi.verifySmsCode(this.passwordRequest.code).then(res => {
              this.disableNext = false
              this.$message({
                type: 'success',
                message: res.result
              })
              this.step = 2
            }).catch(error => {
              this.disableNext = false
              console.log(error)
            })
          }
        }
      })
    },

    saveChange() {
      this.$refs.savePassword.validate(valid => {
        if (valid) {
          const passwordRequest = {
            oldPassword: this.passwordRequest.oldPassword,
            newPassword: this.passwordRequest.newPassword
          }
          this.saveBtn = true
          userApi.updatePassword(passwordRequest).then(res => {
            this.saveBtn = false
            this.$message({
              type: 'success',
              message: res.result
            })
            this.step = 3
            this.$router.push({ path: '/ucenter/profile' })
          }).catch(error => {
            this.saveBtn = false
            console.log(error)
          })
        }
      })
    }

  }
}
</script>

<style scoped>

.show-pwd {
  position: absolute;
  right: 10px;
  top: 7px;
  font-size: 16px;
  color: #889aa4;
  cursor: pointer;
  user-select: none;
}

</style>
